<template>
  <!-- <el-upload v-model:file-list="fileList" multiple list-type="text" :on-success="uploadSuccess"
    :on-change="uploadChange" :auto-upload="false" :show-file-list="false">
    <el-button type="primary" round>批量文件上传</el-button>
  </el-upload> -->

  <el-button type="primary" @click="promptFolderSelection"
    >选择文件夹</el-button
  >
  <input
    type="file"
    ref="folderInput"
    webkitDirectory
    style="display: none"
    @change="handleFolderSelect"
  />
  <div>
    <h3>选择的文件：</h3>
    <ul>
      <li v-for="file in files" :key="file.name">{{ file.name }}</li>
    </ul>
  </div>

  <div class="file-list">
    <div class="file-item" v-for="(f, index) in fileList" :key="index">
      <div class="file-name">
        {{ f.name }}
      </div>

      <el-select
        v-model="fileList[index].cate"
        placeholder="选择csv文件分类"
        size="large"
        style="width: 240px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-button style="margin-left: 10px" type="warning" round
        >检测错误</el-button
      >

      <el-button type="primary" round @click="saveRecord(index)"
        >数据入库</el-button
      >
      <div class="progress-wrapper" v-if="renderOK">
        <el-progress
          v-if="statusList[index] !== 500"
          :text-inside="true"
          :stroke-width="26"
          :percentage="progressList[index]"
        />
        <el-progress
          v-else
          status="exception"
          :text-inside="true"
          :stroke-width="26"
          :percentage="progressList[index]"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import axios from "axios";

import type {
  UploadFile,
  UploadFiles,
  UploadProps,
  UploadUserFile
} from "element-plus";
import { handle_all_files } from "@/api/product";
const emit = defineEmits(["update:modelValue", "handleChange"]);
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: () => false
  }
});

const files = ref([]);
const folderInput = ref(null);

const promptFolderSelection = () => {
  folderInput.value.click();
};

const handleFolderSelect = event => {
  files.value = Array.from(event.target.files);
  console.log(files.value);
  const allFilePath = files.value.map(f => f.webkitRelativePath);
  handle_all_files(allFilePath).then(res => {});
};

const progressList = ref([]);
const statusList = ref([]);
const renderOK = ref(false);

// agent_info
const options = [
  {
    value: "registrant_info",
    label: "商标注册人信息"
  },
  {
    value: "international_base_info",
    label: "国际注册基本信息"
  },
  {
    value: "priority_info",
    label: "注册商标优先权信息"
  },
  {
    value: "co_owner_info",
    label: "注册商标共有人信息"
  },
  {
    value: "commodity_service_info",
    label: "注册商标商品服务信息"
  },
  {
    value: "base_info",
    label: "注册商标基本信息"
  },
  {
    value: "agent_info",
    label: "商标代理人信息"
  }
];
interface FileExtralType extends UploadUserFile {
  cate: string;
}

const fileList = ref<FileExtralType[]>([]);

type ImageInfo = {
  name: string;
  url: string;
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const saveRecord = async (index: number) => {
  const file = fileList.value[index];
  debugger;
  const formData = new FormData();
  formData.append("file", file.raw);
  formData.append("cate", file.cate);
  try {
    const response = await axios.post("/api/list_all_file", formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      onUploadProgress: progressEvent => {
        progressList.value[index] = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
      }
    });
    statusList.value[index] = 200;
    console.log("File uploaded successfully:", response.data);
  } catch (error) {
    statusList.value[index] = 500;
    console.error("Error uploading file:", error);
  }
};

watch(
  () => props.modelValue,
  newValue => {
    const imageList = newValue.map(imageRaw => {
      const imageInfo = imageRaw as ImageInfo;
      if (imageInfo.url.indexOf("/_upload") !== -1) {
        return imageInfo;
      }
      return {
        url: `/_upload${imageInfo.url}`,
        name: imageInfo.name
      };
    });
    fileList.value = [...imageList] as any;
  },
  { immediate: true, deep: true }
);

const uploadChange = () => {
  renderOK.value = true;
};

const uploadSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  // console.log(response);
  // console.log(uploadFile);
  // console.log(uploadFiles);

  // const urls = uploadFiles.map((file: UploadFile) => {
  //   if (file.response) {
  //     return {
  //       name: file.name,
  //       url: file.response.data.link
  //     };
  //   }
  //   return file;
  // });
  emit("update:modelValue", urls);
};
</script>

<style lang="css" scoped>
.progress-wrapper {
  margin-left: 20px;
  min-width: 200px;
  flex: 1;
}

.file-list {
  margin: 30px 0;
  padding: 10px;
  background-color: #fff;
}

.file-name {
  margin-right: 10px;
  width: 300px;
  /* background: #e1e1e1; */
}

.file-item {
  padding: 10px 20px;
  border: solid 1px #efefef;
  border-radius: 10px;
  margin-bottom: 5px;

  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}
</style>
